package com.syqc.sensor.demp

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.TempDay
import com.syqc.entity.TypeInfo
import com.syqc.monitor.R
import com.syqc.utils.DataUtil
import com.syqc.net.ServiceHelper
import com.syqc.utils.TimeUtil
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.BehaviorSubject
import kotlin.concurrent.thread

/**
 *@author joker
 *@time   2024/6/5 15:29
 *@desc
 */
class DampVM : AutoDisposeViewModel() {

    private val hourTime = 3600000L
    private val dayTime = 24 * hourTime

    //是否是开始时间
    var isStart = true

    //时间列表
    val timeList by lazy { TimeUtil.instance.getTimeList() }

    //开始时间
    private val startTime by lazy { BehaviorSubject.create<String>() }
    fun startObserve(): Observable<String> = startTime.hide()

    //结束时间
    private val endTimeSub by lazy { BehaviorSubject.create<String>() }
    fun endObserve(): Observable<String> = endTimeSub.hide()

    //当前时间
    private fun nowTime() = System.currentTimeMillis()

    init {
        endSimpleTime(0)
        startSimpleTime(0)
    }

    private fun startSimpleTime(day: Int) {
        startTime.onNext(TimeUtil.instance.simpleTime(nowTime() - day * dayTime))
    }

    private fun endSimpleTime(day: Int) {
        endTimeSub.onNext(TimeUtil.instance.simpleTime(nowTime() - day * dayTime))
    }

    private fun endSimpleTime() {
        endTimeSub.onNext(TimeUtil.instance.simpleTime(nowTime()))
    }

    fun nowTimeFormat(): String {
        return TimeUtil.instance.simpleTime(nowTime())
    }

    fun chooseTime(position: Int) {
        val chooseTime = timeList[position]
        when (chooseTime.timeType) {
            2 -> {
                startSimpleTime(chooseTime.timeNum)
                endSimpleTime(chooseTime.timeNum)
            }

            4 -> {
                startSimpleTime(chooseTime.timeNum)
                endSimpleTime(1)
            }

            else -> {
                startSimpleTime(chooseTime.timeNum)
                endSimpleTime()
            }
        }
    }

    fun isOkStart(startTime: String, endTime: String): Boolean {
        val time: Long = TimeUtil.instance.getDiffTime(startTime, endTime, true)
        if (time < 0) {
            toast(R.string.toast_start_less_than_end_time)
            return true
        }
        return false
    }

    /**
     * 判断时间是否合理
     */
    fun isTimeOk(startTime: String, endTime: String): Boolean {
        val time: Long = TimeUtil.instance.getDiffTime(startTime, endTime, true)
        if (time < 0) {
            toast(R.string.toast_start_less_than_end_time)
            return true
        }
        //判断时差是否大于7天
        if (time > 604800000) {
            toast(R.string.toast_more_than_seven_time)
            return true
        }
        return false
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    private val _dataLive = MutableLiveData<Boolean>()
    val dataLive: LiveData<Boolean> = _dataLive
    var carId = ""
    var carName = ""
    var teamName = ""

    fun isParamOk(startTime: String, endTime: String) {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return
        }
        if (isTimeOk(startTime, endTime)) return
        getTempStats(carId, startTime, endTime)
    }


    //获取油量
    private fun getTempStats(carId: String, startTime: String, endTime: String) {
        toastLoading(true)
        ServiceHelper.getRepository()
            .getTempStats(4, carId, startTime.substring(0, 10), endTime.substring(0, 10))
            .autoDispose(this)
            .subscribe({ it ->
                if (isHasListData(it, R.string.toast_no_oil_data)) {
                    toastLoading(false)
                    return@subscribe
                }
                if (it[0].cfg == null) {
                    toast(R.string.toast_no_set_analog)
                    toastLoading(false)
                    return@subscribe
                }
                handleData(it)

            }, error)

    }

    private val tempMap = hashMapOf<String, ArrayList<TempDay>>()
    fun handleData(dayInfo: ArrayList<TempDay>) {
        tempMap.clear()
        timeMap.clear()
        val typeInfos = mutableListOf<TypeInfo>()
        thread {
            dayInfo.forEach {
                if (it.day != null) {
                    if (it.typeId != null && isNotHad(typeInfos, it.typeId)) {
                        val name = if (it.cfg != null) {
                            val map = GsonUtil.formJsonMap(it.cfg)
                            val name = map["name"] ?: ""
                            name.toString()
                        } else ""
                        typeInfos.add(TypeInfo(it.typeId, name))
                    }
                }
            }
            typeInfos.forEach { type ->
                dayInfo.forEach {
                    if (it.day != null) {
                        if (it.typeId == type.typeId) {
                            val arrays = tempMap[it.day]
                            if (arrays == null) {
                                tempMap[it.day] = arrayListOf(it)
                                timeMap[it.day] = false
                            } else {
                                arrays.add(it)
                                tempMap[it.day] = arrays
                            }
                        }
                    }
                }
            }

            DataUtil.typeInfos = typeInfos

            tempNodeMap.clear()
            if (tempMap.isEmpty()) {
                toast(R.string.toast_navi_no_data)
                toastLoading(false)
                return@thread
            }

            tempMap.forEach { item ->
                val cfgs = ArrayList<String>()
                item.value.forEach {
                    cfgs.add(it.cfg ?: "")
                }
                getNode(carId, item.key, cfgs.toString())
            }
        }


    }

    //列表是否已经包含
    private fun isNotHad(list: MutableList<TypeInfo>, typeId: String): Boolean {
        for (info in list) {
            if (typeId == info.typeId) return false
        }
        return true
    }

    private val tempNodeMap = hashMapOf<String, ArrayList<String>>()
    private val timeMap = HashMap<String, Boolean>()

    private fun getNode(carId: String, day: String, cfg: String) {
        ServiceHelper.getRepository().getNodesMap(carId, day, cfg)
            .autoDispose(this).subscribe({
                tempNodeMap[day] = it
                timeMap[day] = true
                isHasDataOK()
            }, {
                timeMap[day] = true
                isHasDataOK()
            })
    }

    private fun isHasDataOK() {
        var isValue = true
        timeMap.values.forEach {
            isValue = it && isValue
        }
        if (isValue) {
            toastLoading(false)
            if (tempNodeMap.values.isEmpty()) {
                toast(R.string.toast_navi_no_data)
                return
            }
            if (!isHadData()) {
                toast(R.string.toast_navi_no_data)
                return
            }
            DataUtil.tempNodeMap = tempNodeMap
            _dataLive.postValue(true)
        }
    }

    fun isHadData(): Boolean {
        tempNodeMap.values.forEach {
            if (it.isNotEmpty()) return true
        }
        return false
    }
}